package com.kgc.scd.service.impl;

import com.kgc.scd.delay.OrderDelay;
import com.kgc.scd.service.OrderService;
import com.kgc.scd.service.TaskService;
import com.kgc.scd.util.RedisUtils;
import com.kgc.scd.vo.ShopOrderVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Executors;

/**
 * Created On : 2022/11/22.
 * <p>
 * Author : Administrator
 * <p>
 * Description: TaskServiceImpl
 */
@Service
@Slf4j
public class TaskServiceImpl implements TaskService{

    private  TaskServiceImpl taskService;
    // 创建延时队列
    private DelayQueue<OrderDelay> orderDelayQueue =  new DelayQueue<OrderDelay>();

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private OrderService orderService;
    @PostConstruct
    private void init() {
        taskService = this;
        Executors.newSingleThreadExecutor().execute(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                        String orderId=orderDelayQueue.take().orderHandle();
                        if (StringUtils.isNotBlank(orderId)){

                            ShopOrderVO shopOrderVO=orderService.involveGetShopOrderById(orderId);
                            log.info("shopOrderVo"+shopOrderVO);
                            if (shopOrderVO.getShoppingStatus().equals("未支付")){

                                redisUtils.del(orderId);
                                orderService.involveDelShopOrderById(orderId);
                                log.info("[通知]尊敬的用户,由于您未在规定的时间内支付订单,已取消该订单");
                            }
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        });
    }

    @Override
    public void addTask(OrderDelay task){
        if(orderDelayQueue.contains(task)){
            return;
        }
        orderDelayQueue.add(task);
    }

    @Override
    public void removeTask(OrderDelay task){
        orderDelayQueue.remove(task);
    }
}
